<template>
    <el-dialog class="ui-shift-exchange-dlg" v-model="dialogVisible" top="3rem" :title="dialogTitle" ref="dialog" @opened="init" :beforeClose="beforeClose" @closed="finalThings">
        <el-form :model="submit">
        <div class="left-body">
            <div ref="elToolbar" class="co-el-toolbar">
                <el-form :model="params">
                    <div class="co-toolbar co-box-row">
                        <el-form-item label="仓库:" size="default">
                            <el-select v-model="params.store_id" style="width: 120px;" @change="loadGoods">
                                <el-option
                                    v-for="item in stores"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item label=""  size="default">
                            <el-select class="co-cat-select" v-model="params.cat_id" style="width:110px" @change="loadGoods">
                                <el-option v-for="item in categorys" :key="item.id" :label="item.name" :value="item.id" />
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-input v-model="params.filter" clearable></el-input>
                        </el-form-item>
                        <el-button type="primary">搜索</el-button>
                    </div>
                </el-form>
            </div>
            <el-table :data="data" size="small" height="30rem">
                <el-table-column prop="name" label="商品名称"></el-table-column>
                <el-table-column label="库存数目" align="center"  width="150">
                    <template #default="{row}">
                        <el-input-number v-model="row.new_num" size="small" :max="row.store_num" @change="setNewSale(row)" />
                    </template>
                </el-table-column>
                <el-table-column prop="num_sale" label="售出数目" align="right" width="125">
                    <template #default="{row}">
                        <div v-if="row.new_num == row.store_num">{{ row.num_sale }}</div>
                        <div v-else>{{ row.num_sale }}<span style="color:var(--el-color-primary)"> + {{ row.store_num - row.new_num }}</span></div>
                    </template>
                </el-table-column>
                <el-table-column prop="amount" label="销售收入" align="right"  width="125" :formatter="rmbFormatter"></el-table-column>
                <el-table-column prop="sale_price" label="操作" align="center"  width="70">
                    <template #default="{row}">
                        <el-link type="primary" size="small">详情</el-link>
                    </template>
                </el-table-column>
            </el-table>
            <div class="ui-pagination-ctn box-row">
                <el-pagination
                    v-model:current-page="params.page" :page-size="params.limit" :page-sizes="[13, 50, 100, 200]"
                    layout="sizes, total, prev, pager, next" :total="total" 
                    @size-change="loadGoods" @current-change="loadGoods"
                ></el-pagination>
            </div>
        </div>
        <div class="right-bar">
            <el-scrollbar>
                <el-collapse v-model="collapseItems">
                <el-collapse-item title="商品销售汇总" :name="0">
                    <div>现金订单销售:</div><div>
                        <template v-if="submit.sum_amount > 0.00001">
                            <span v-rmb="shift.amount_sale + submit.sum_amount"></span>
                        </template>
                        <template v-else><span v-rmb="shift.amount_sale"></span></template>
                    </div>
                    <div>现金退货:</div><div v-rmb="shift.amount_refund"></div>
                    <div>线上订单销售:</div><div v-rmb="shift.amount_online_sale"></div>
                    <div>线上退货:</div><div v-rmb="shift.amount_online_refund"></div>
                    <div>网费销售(不计收支):</div><div v-rmb="shift.amount_member_sale"></div>
                    <div>网费退货(不计收支):</div><div v-rmb="shift.amount_member_sale"></div>
                </el-collapse-item>
                <el-collapse-item title="其它收支汇总" :name="1">
                    <div>现金进货:</div><div v-rmb="shift.amount_purchase"></div>
                    <div>现金出货:</div><div v-rmb="shift.amount_sell"></div>
                    <div>盘溢(不计收支):</div><div v-rmb="shift.amount_stock_in"></div>
                    <div>盘损(不计收支):</div><div v-rmb="shift.amount_stock_out"></div>
                </el-collapse-item>
                <el-collapse-item title="实际营收" :name="2">
                    <div>现金收入:</div><div v-rmb="shift.amount_sale - shift.amount_refund"></div>
                    <div>线上收入:</div><div v-rmb="shift.amount_online_sale - shift.amount_online_refund"></div>
                    <div>网费收入:</div><div v-rmb="shift.amount_member_sale - shift.amount_member_refund"></div>
                </el-collapse-item>
                <el-collapse-item title="实际营收" :name="3">
                    <div>钱箱余额:</div><div v-rmb="shift.amount"></div>
                    <div>线上余额:</div><div v-rmb="shift.amount_online"></div>
                </el-collapse-item>
            </el-collapse>
            </el-scrollbar>
            <div class="form-panel">
                <el-form-item label="钱箱预留:" size="small">
                    <el-input-number v-model="submit.keep_cash" :min="0" :value-on-clear="0" :step="0.01" step-strictly :controls="false"></el-input-number>
                </el-form-item>
                <el-form-item label="接班人:" size="small">
                    <el-select v-model="submit.uid">
                        <el-option v-for="item in accounts" :key="item.id" :value="item.id" :label="item.realname ?? item.username"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="备注:" size="small">
                    <el-input v-model="submit.desc"></el-input>
                </el-form-item>
            </div>
        </div>
        </el-form>
        <template #footer>
            <div class="box-row">
                <div style="flex:1"></div>
                <el-button size="default" type="primary" @click="onSure">确认交班</el-button>
                <el-button size="default" type="danger" @click="onCancel">取消</el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script>
import { reactive, computed, toRefs } from 'vue-demi';
import { useSocket } from '../../uiframe/services/socket';
import directives from '../../uiframe/services/directives';
import { ElMessage } from 'element-plus';
export default {
    directives,
    props:{
        q:Object,
        done: Function,
        payload:Object
    },
    setup:(props)=>{
        const onmessage = (msg) => ElMessage({ type: msg.success ? 'success' : 'error', message: msg.message }),
        data = reactive({
            dialogVisible: true,
            dialogTitle:'交班',
            dialog:null, elForm:null,collapseItems:[0,2,3],
            params:{
                store_id:-1,
                cat_id:-1,
                page:1,
                limit:13,
                filter:'',
            },
            data:[],
            total:0,
            stores:[],
            categorys:[],
            accounts:[],
            shift:{},
            submit:{
                uid:0,
                keep_cash:0,
                sale:{},
                sum_amount:0,
                desc:''
            }
        }),rules =[

        ],
        methods = {
            onSure:()=>{
                if(data.loading) return;
                data.loading = true;
                let payload = {uid:data.submit.uid, keep_cash:data.submit.keep_cash, desc:data.submit.desc}, sales = [];
                for(let store_id in data.submit.sale){
                    let store = data.submit.sale[store_id];
                    for(let goods_id in store){
                        sales.push({store_id:parseInt(store_id), goods_id:parseInt(goods_id), num:store[goods_id].num, price:store[goods_id].price});
                    }
                }
                payload.sales = sales;
                useSocket().then(socket=>socket.rpc('shift.exchange',payload).then(res=>{
                    data.loading = false;
                    onmessage(res)
                    if(res.success){
                        data.dialogVisible = false;
                    }
                }));
            },
            onCancel:()=>{
                props.q.reject({});
                data.dialogVisible = false;
            },
            init:()=>{

            },
            beforeClose:(next)=>{
                next();
            },
            finalThings:()=>props.done(),
            onSelectStore:(id)=>{
                methods.loadGoods();
            },
            loadGoods:()=>{
                useSocket().then(socket=>socket.rpc('shift.goods',data.params).then(({success, data:result})=>{
                    data.data = result.data.map(v=>{
                        let s = data.submit.sale;
                        if(s.hasOwnProperty(v.store_id) && s[v.store_id].hasOwnProperty(v.goods_id)){
                            v.new_num = v.store_num - s[v.store_id][v.goods_id].num;
                        }else{
                            v.new_num = v.store_num;
                        }
                        return v;
                    });
                    data.total = result.total;
                    data.loading = false;
                }));
            },
            setNewSale:(row)=>{
                let s = data.submit.sale, num = row.store_num - row.new_num;
                if(num > 0){
                    if(!s.hasOwnProperty(row.store_id)){s[row.store_id] = {};}
                    s[row.store_id][row.goods_id] = {num, price: num * row.sale_price};
                } else {
                    delete s[row.store_id][row.goods_id];
                }
                data.submit.sum_amount = Object.values(s).reduce((a,v)=>a+Object.values(v).reduce((a1,v1)=>a1+v1.price,0),0);
            },
            rmbFormatter:(r,c,v)=>v.toFixed(2)
        };
        
        useSocket().then(socket=>{
            Promise.all([
                socket.rpc('stores',{}),
                socket.rpc('category',{}),
                socket.rpc('accounts', {}),
                socket.rpc('shift.read', {})
            ]).then(([{success:s1, data:res1},{success:s2, data:categorys},{success:s3, data:{data:accounts}},{success:s4, data:shift}])=>{
                if(s1 && s2 && s3 && s4){
                    data.stores = res1.filter(v=>v.prop==1);
                    data.categorys = categorys;
                    data.params.cat_id = categorys[0].id;
                    
                    if(data.stores.length > 1){
                        data.params.store_id = data.stores[0].id
                        methods.loadGoods();
                    }

                    data.accounts = accounts
                    data.submit.uid = accounts[0].id
                    data.shift = shift;
                    data.keep_cash = data.last_amount;
                }
            });
        });
        return {
            ...toRefs(data),
            ...methods,
            rules
        }
    }
}
</script>
<style lang="scss">
.ui-shift-exchange-dlg{
    width:66rem;max-width: 66rem;
    .el-dialog__header{
        padding: .5rem 1rem 1rem 1rem;
        .el-dialog__headerbtn{
            line-height: 1rem;
            width:54px;height:24px;
        }
    }
    .el-dialog__body {
        padding: 0 1.5rem 1rem 1.5rem;
        > form{
            display:grid;
            grid-template-columns: auto 15rem;
            .left-body{
                border-top:1px solid var(--el-border-color);
                border-left:1px solid var(--el-border-color);
                border-right:1px solid var(--el-border-color);
                .ui-pagination-ctn{
                    border-bottom:1px solid var(--el-border-color);
                }
            }
            .right-bar{
                border:1px solid var(--el-border-color);
                border-left: none;
                display: flex;
                flex-direction: column;
                .el-collapse-item__header{
                    font-weight: bold;
                    padding:0 .5rem;
                    line-height:1.5rem;
                    height:32px;
                }
                .el-collapse-item__content{
                    display: grid;
                    padding:0 .5rem 0 1rem;
                    grid-template-columns: auto 5rem;
                    :nth-child(2n){
                        text-align: right;
                        color:var(--el-color-primary)
                    }
                }
                .el-scrollbar{
                    height:26.7rem;
                    .el-scrollbar__wrap{
                        padding:0;
                    }
                }
                .form-panel{
                    border-top: 1px solid var(--el-border-color);
                    flex:1;
                    padding:.5rem;
                    .el-input-number--small{
                        width:100%;
                        .el-input__inner{
                            text-align: left;
                        }
                    }
                }
            }
        }
    }
    .el-dialog__footer{
        padding: .5rem 1rem 1rem 1rem;
    }
}
</style>